package com.hgc.ch03;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by 01367627 on 2019/7/10.
 */
public class MySafeIncrement {
    private AtomicInteger ai = new AtomicInteger(0);

    void increment(){
        int i = getValue();
        if(!ai.compareAndSet(i,i+1)){
            increment();
        }
    }

    int getValue(){
        return ai.get();
    }

    public static void main(String[] args) throws InterruptedException {
        MySafeIncrement msi = new MySafeIncrement();
        for(int i=0;i<1000;i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    msi.increment();
                }
            }).start();
        }
        Thread.sleep(500);
        System.out.println(msi.getValue());
    }

}
